﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using STS.Model;
using System;

namespace STS.ViewModel
{
    public class BadaniaViewModel : BaseViewModel
    {
        private ObservableCollection<Badania> _badaniaItems;
        public ObservableCollection<Badania> BadaniaItems
        {
            get
            {
                if (_badaniaItems == null)
                {
                    _badaniaItems = new ObservableCollection<Badania>();
                }
                return _badaniaItems;
            }
            set
            {
                _badaniaItems = value;
                NotifyPropertyChanged("BadaniaItems");
            }
        }

        public void FindBadaniaItems()
        {
            var badaniaDB = from badania in ModelInstance.DataContext.BadaniaItems
                                select badania;
            BadaniaItems = new ObservableCollection<Badania>(badaniaDB);
            Debug.WriteLine("Znalazłem Badania, size = " + BadaniaItems.Count);
        }

        public Badania FindBadaniaByIdBadania(int badaniaId)
        {
            var badaniaDB = from badania in ModelInstance.DataContext.BadaniaItems
                                where badania.IdBadania == badaniaId
                                select badania;
            return badaniaDB.SingleOrDefault<Badania>();
        }

        public void UpdateBadania(Badania updateBadania)
        {
            Badania old = FindBadaniaByIdBadania(updateBadania.IdBadania);
            SetEntityPropertities(ref old, updateBadania);
            SaveChangesToDB();
        }

        public void AddBadania(Badania badania)
        {
            RemoveAllBadania();
            ModelInstance.DataContext.BadaniaItems.InsertOnSubmit(badania);
            SaveChangesToDB();
            BadaniaItems.Add(badania);
        }

        public void RemoveBadania(Badania badania)
        {
            BadaniaItems.Remove(badania);
            ModelInstance.DataContext.BadaniaItems.DeleteOnSubmit(badania);
            SaveChangesToDB();
        }

        public void RemoveAllBadania()
        {
            var badaniaDB = from badania in ModelInstance.DataContext.BadaniaItems
                                select badania;

            foreach (Badania _badania in badaniaDB)
            {
                ModelInstance.DataContext.BadaniaItems.DeleteOnSubmit(_badania);
            }

            try
            {
                SaveChangesToDB();
                BadaniaItems.Clear();
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
            }
        }

    }
}
